package org.itzixi.controller;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.itzixi.MinIOConfig;
import org.itzixi.MinIOUtils;
import org.itzixi.api.feign.UserInfoMicroServiceFeign;
import org.itzixi.exceptions.GraceException;
import org.itzixi.grace.result.GraceJSONResult;
import org.itzixi.grace.result.ResponseStatusEnum;
import org.itzixi.pojo.vo.UsersVO;
import org.itzixi.pojo.vo.VideoMsgVO;

import org.itzixi.utils.FFmpegVideoUtil;
import org.itzixi.utils.JcodecVideoUtil;
import org.itzixi.utils.JsonUtils;
import org.itzixi.utils.QrCodeUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("file")
public class FileController {

    @Resource
    private MinIOConfig minIOConfig;
    @Resource
    private UserInfoMicroServiceFeign  userInfoMicroServiceFeign;
    @PostMapping("uploadFace1")
    public GraceJSONResult uploadFace1(@RequestParam("file") MultipartFile file,
                                 String userId ,
                                 HttpServletRequest  request) throws Exception {
        String fileName = file.getOriginalFilename();
        String suffixName= fileName.substring(fileName.lastIndexOf("."));
        String newFileName = userId + suffixName;
        String rootPath = "E:\\IdeaProjects\\wechat-dev\\pic";
        String filePath = rootPath + "\\" + newFileName;
        File newFile= new File(filePath);
        if(newFile.getParentFile().exists()){
            newFile.getParentFile().mkdirs();
        }
        file.transferTo(newFile);
        return GraceJSONResult.ok();
    }


    @PostMapping("uploadFace")
    public GraceJSONResult uploadFace(@RequestParam("file") MultipartFile file,
                                       String userId ,
                                       HttpServletRequest  request) throws Exception {
        if(StringUtils.isBlank(userId)){
            return GraceJSONResult.errorCustom(ResponseStatusEnum.FILE_UPLOAD_FAILD);
        }


        String filename = file.getOriginalFilename();
        if(StringUtils.isBlank(filename)){
            return GraceJSONResult.errorCustom(ResponseStatusEnum.FILE_UPLOAD_FAILD);
        }
//        filename="face"+File.separator+userId+File.separator+filename; separator是\\ 无法使用
        filename="face"+"/"+userId+"/"+filename;
        MinIOUtils.uploadFile(minIOConfig.getBucketName(),
                filename,
                file.getInputStream());
        String faceUrl = minIOConfig.getFileHost()+"/"+minIOConfig.getBucketName()+"/"+filename;

        /**
         * 微服务远程调用更新头像到数据库 OpenFeign
         *
         */
        GraceJSONResult jsonResult = userInfoMicroServiceFeign.updateFace(userId,faceUrl);
        Object data = jsonResult.getData();
        String json = JsonUtils.objectToJson(data);
        UsersVO usersVO = JsonUtils.jsonToPojo(json, UsersVO.class);
        return GraceJSONResult.ok(usersVO);
    }

    @PostMapping("generatorQrCode")
    public String generatorQrCode(String wechatNumber, String userId) throws Exception {
        //构建map对象
        Map<String,String> map=new HashMap<>();
        map.put("wechatNumber",wechatNumber);
        map.put("userId",userId);
        //将map转换为json字符串
        String data = JsonUtils.objectToJson(map);
        //生成二维码
        String qrCodePath = QrCodeUtils.generateQRCode(data);
        //将二维码上传到minio
        if(StringUtils.isNotBlank(qrCodePath)){
            String uuid= UUID.randomUUID().toString();
            String objectName="wechatNumber"+"/"+userId+"/"+uuid+".png";
            String imageQrCodeUrl=MinIOUtils.uploadFile(minIOConfig.getBucketName(),
                    objectName,
                    qrCodePath,
                    true);
            return imageQrCodeUrl;
        }
        return null;
    }

    @PostMapping("uploadFriendCircleBg")
    public GraceJSONResult uploadFriendCircleBg(@RequestParam("file") MultipartFile file,
                                      String userId) throws Exception {
        if(StringUtils.isBlank(userId)){
            return GraceJSONResult.errorCustom(ResponseStatusEnum.FILE_UPLOAD_FAILD);
        }


        String filename = file.getOriginalFilename();
        if(StringUtils.isBlank(filename)){
            return GraceJSONResult.errorCustom(ResponseStatusEnum.FILE_UPLOAD_FAILD);
        }
//        filename="face"+File.separator+userId+File.separator+filename; separator是\\ 无法使用
        filename="friendCircleBg"+"/"+userId+"/"+dealWithoutFilename(filename);
        String imageUrl = MinIOUtils.uploadFile(minIOConfig.getBucketName(),
                filename,
                file.getInputStream(),true);


        /**
         * 微服务远程调用更新头像到数据库 OpenFeign
         *
         */
        GraceJSONResult jsonResult = userInfoMicroServiceFeign.uploadFriendCircleBg(userId,imageUrl);
        Object data = jsonResult.getData();
        String json = JsonUtils.objectToJson(data);
        UsersVO usersVO = JsonUtils.jsonToPojo(json, UsersVO.class);
        return GraceJSONResult.ok(usersVO);
    }

    @PostMapping("uploadChatBg")
    public GraceJSONResult uploadChatBg(@RequestParam("file") MultipartFile file,
                                                String userId) throws Exception {
        if(StringUtils.isBlank(userId)){
            return GraceJSONResult.errorCustom(ResponseStatusEnum.FILE_UPLOAD_FAILD);
        }


        String filename = file.getOriginalFilename();
        if(StringUtils.isBlank(filename)){
            return GraceJSONResult.errorCustom(ResponseStatusEnum.FILE_UPLOAD_FAILD);
        }
//        filename="face"+File.separator+userId+File.separator+filename; separator是\\ 无法使用
        filename="chatBg"+"/"+userId+"/"+dealWithoutFilename(filename);
        String imageUrl = MinIOUtils.uploadFile(minIOConfig.getBucketName(),
                filename,
                file.getInputStream(),true);


        /**
         * 微服务远程调用更新头像到数据库 OpenFeign
         *
         */
        GraceJSONResult jsonResult = userInfoMicroServiceFeign.uploadChatBg(userId,imageUrl);
        Object data = jsonResult.getData();
        String json = JsonUtils.objectToJson(data);
        UsersVO usersVO = JsonUtils.jsonToPojo(json, UsersVO.class);
        return GraceJSONResult.ok(usersVO);
    }


    @PostMapping("uploadFriendCircleImage")
    public GraceJSONResult uploadFriendCircleImage(@RequestParam("file") MultipartFile file,
                                        String userId) throws Exception {
        if(StringUtils.isBlank(userId)){
            return GraceJSONResult.errorCustom(ResponseStatusEnum.FILE_UPLOAD_FAILD);
        }


        String filename = file.getOriginalFilename();
        if(StringUtils.isBlank(filename)){
            return GraceJSONResult.errorCustom(ResponseStatusEnum.FILE_UPLOAD_FAILD);
        }
//        filename="face"+File.separator+userId+File.separator+filename; separator是\\ 无法使用
        filename="friendCircleImage"+"/"+userId+"/"+dealWithoutFilename(filename);
        String imageUrl = MinIOUtils.uploadFile(minIOConfig.getBucketName(),
                filename,
                file.getInputStream(),true);

        return GraceJSONResult.ok(imageUrl);
    }
    ///file/uploadChatPhoto?userId=" + userId
    @PostMapping("uploadChatPhoto")
    public GraceJSONResult uploadChatPhoto(@RequestParam("file") MultipartFile file,
                                                   String userId) throws Exception {
        String imageUrl = uploadForChatFiles(file, userId, "photo");

        return GraceJSONResult.ok(imageUrl);
    }

    //file/uploadChatVideo?userId=" + userId
    @PostMapping("uploadChatVideo")
    public GraceJSONResult uploadChatVideo(@RequestParam("file") MultipartFile file,
                                           String userId) throws Exception {

        String videoUrl = uploadForChatFiles(file, userId, "video");


        //视频截帧
        String coverName = UUID.randomUUID().toString()+".jpg"; // 封面图片名称
        String coverPath = JcodecVideoUtil.videoFramesPath + "/" + "videos" +"/"+ coverName; // 封面图片路径
        File coverFile = new File(coverPath);

        if(!coverFile.getParentFile().exists()){
            coverFile.getParentFile().mkdirs();
        }

        JcodecVideoUtil.fetchFrame(file,coverFile);

        //上传封面图片到minio
        String coverUrl = MinIOUtils.uploadFile(minIOConfig.getBucketName(),
                coverName,
                new FileInputStream(coverFile),true);

        VideoMsgVO videoMsgVO = new VideoMsgVO();
        videoMsgVO.setVideoPath(videoUrl);
        videoMsgVO.setCover(coverUrl);

        return GraceJSONResult.ok(videoMsgVO);
    }

//    file/uploadChatVoice?userId=
    @PostMapping("uploadChatVoice")
    public GraceJSONResult uploadChatVoice(@RequestParam("file") MultipartFile file,
                                           String userId) throws Exception {
        String voiceUrl = uploadForChatFiles(file, userId, "voice");

        return GraceJSONResult.ok(voiceUrl);
    }

    private String uploadForChatFiles(MultipartFile file, String userId, String fileType) throws Exception {
        if(StringUtils.isBlank(userId)){
            GraceException.display(ResponseStatusEnum.FILE_UPLOAD_FAILD);
        }

        String filename = file.getOriginalFilename();
        if(StringUtils.isBlank(filename)){
            GraceException.display(ResponseStatusEnum.FILE_UPLOAD_FAILD);
        }
        //        filename="face"+File.separator+userId+File.separator+filename; separator是\\ 无法使用
        filename="chat"
                +"/"+userId
                +"/"+fileType
                +"/"+dealWithoutFilename(filename);
        String fileUrl = MinIOUtils.uploadFile(minIOConfig.getBucketName(),
                filename,
                file.getInputStream(),true);

        return fileUrl;
    }


    private String dealWithFilename(String filename){
        String suffixName= filename.substring(filename.lastIndexOf("."));
        String fName = filename.substring(0,filename.lastIndexOf("."));
        String uuid= UUID.randomUUID().toString();
        return fName+"-"+uuid+suffixName;
    }

    private String dealWithoutFilename(String filename){
        String suffixName= filename.substring(filename.lastIndexOf("."));
        String uuid= UUID.randomUUID().toString();
        return uuid+suffixName;
    }
}
